<template>
  <div id="vabOnlyOffice"></div>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  name: "VabOnlyOffice",
  props: {
    option: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      doctype: "",
      docEditor: null,
    };
  },
  beforeDestroy() {
    this.docEditor?.destroyEditor?.();
    this.docEditor = null;
  },
  watch: {
    option: {
      handler: (n) => {
        this.setEditor(n);
        this.doctype = this.getFileType(n.fileType);
      },
      deep: true,
    },
  },
  mounted() {
    if (this.option.url) {
      this.setEditor(this.option);
    }
  },
  methods: {
    async setEditor(option) {
      // 1. 分割 URL 提取 bucketName 和 fileName
      const urlParts = option.url.split("/");
      // 2. 提取 bucketName（URL 中第4部分，索引3）
      const bucketName = urlParts[3];
      // 3. 提取 fileName（URL 中第5部分及以后，索引4）
      const fileName = urlParts.slice(4).join("/");
      console.log("提取的 bucketName:", bucketName); 
      console.log("提取的 fileName:", fileName);

      const key = `${bucketName}:${fileName}_${Date.now()}`;

      const token = getToken();
      console.log("获取的 token:", token); 

      // 销毁旧实例
      this.docEditor?.destroyEditor?.();
      this.docEditor = null;

      // 获取文档类型（OnlyOffice 7.3 要求的格式）
      this.doctype = this.getFileType(option.type);

      // 构建配置
      const config = {
        events: {
          onError: (event) => {
            console.error("OnlyOffice错误:", event);
          },
          onSavingFailed: (event) => {
            console.error("保存失败:", event);
            // 获取详细的错误信息
            if (event.data && event.data.errorCode) {
              console.error("错误代码:", event.data.errorCode);
              console.error("错误描述:", event.data.errorDescription);
            }
          },
          // 添加其他事件监听
          onReady: () => console.log("编辑器已准备好"),
          onDocumentStateChange: (event) =>
            console.log("文档状态变化:", event.data),
        },
        document: {
          fileType: option.type,
          key: key, // 使用提取的 bucketName 和 fileName 生成 key
          title: option.title,
          url: option.url,
          permissions: {
            edit: true,
            review: true,
            comment: true,
            fillForms: true,
            modifyFilter: true,
            modifyContentControl: true,
            download: option.download || false,
            print: option.isPrint || true,
            chat: false,
            copy: true,
            editCommentAuthorOnly: false,
            reviewGroups: "any",
            protect: false,
          },
        },
        documentType: this.doctype, 
        editorConfig: {
          callbackUrl: "http://192.168.1.8:8289/api/files/callback",
          lang: option.lang || "zh-CN",
          customization: {
            autosave: false,
            comments: false,
            help: false,
            plugins: false,
            toolbar: { save: true }, // 显式显示保存按钮
          },

          user: {
            id: (option.user.id || "1").toString(),
            name: option.user.name || "admin",
          },
          mode: option.mode || "edit", // 修正拼写错误
        },
        token: token, // OnlyOffice 会自动将此 Token 添加到请求头

        width: "100%",
        height: "100%",
      };
      console.log("生成的 key:", key);

      console.log("编辑器配置:", config);
      this.docEditor = new DocsAPI.DocEditor("vabOnlyOffice", config);
    },
    getFileType(fileType) {
      const wordTypes = ["doc", "docx", "rtf", "txt", "pdf", "odt"];
      const cellTypes = ["xls", "xlsx", "csv", "ods"];
      const slideTypes = ["ppt", "pptx", "odp"];

      if (wordTypes.includes(fileType)) return "word";
      if (cellTypes.includes(fileType)) return "cell";
      if (slideTypes.includes(fileType)) return "slide";
      return "word";
    },
  },
};
</script>
